package servlet.admin;

import dao.UserDao;
import dao.service.UserDaoImp;
import modle.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author cloudJiang
 * @date 2021/10/10 21:14
 */

@WebServlet("/manage/adminDoUserUpdate")
public class DoUserUpdate extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String userID = request.getParameter("userID");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String userSex = request.getParameter("userSex");
        String userBirthday = request.getParameter("userBirthday");
        String userEmail = request.getParameter("userEmail");
        String userPhone = request.getParameter("userPhone");
        String userAddress = request.getParameter("userAddress");
        int userStatus = Integer.parseInt(request.getParameter("userStatus"));

        //创建用户实体并且加入到数据库
        User user = new User(userID, userName, userPassword, userSex, userBirthday, null, userEmail, userPhone, userAddress, userStatus);
        UserDao userDao = new UserDaoImp();

        //成功或失败从定向
        if (userDao.update(user)) {
            response.sendRedirect("adminDoUserGet?cp=" + request.getParameter("page"));
        } else {
            //获取返回流
            PrintWriter out = response.getWriter();

            out.write("<script>");
            out.write("alert('用户修改失败')");
            out.write("location.href='manage/adminToUserUpdate?id=" + userID + "'");
            out.write("</script>");
        }
    }
}
